import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Response } from 'express';
import { ExceptionMap, SYSTEM_MESSAGE } from 'src/constant';
import { sendExceptionResponse } from 'src/utils';

/**
 * 捕获系统所有未被捕获的异常。处于异常捕获的优先级最低
 */
@Catch()
export class UnknowExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    console.log('exception:', exception);

    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const exceptionError = exception as Error;
    const { statusCode, error } = ExceptionMap.Internal_Server_Error;
    sendExceptionResponse({
      response,
      statusCode: statusCode,
      errorName: error,
      message: exceptionError.message || SYSTEM_MESSAGE.INTERNAL_EXCEPTION,
      detail: exceptionError,
      exception: exceptionError,
    });
  }
}
